#!/usr/bin/env python
# encoding: utf-8

from app.views.api import route_api
from  flask import request,jsonify,g
import requests,json,decimal

from app import db
from app.model import Electronic
from app.model import ElectronicOutCart
from app.model import Project
from app.model import Product
from app.model import Supplier

from app.common.libs.Logging import logger
from app.common.libs.Helper import getFormatDate, stringToDatetime, getCurrentDate
from app.common.libs.ElectronicService import ElectronicService
from app.common.libs.UserService import UserService

from sqlalchemy import func

@route_api.route("/electronic/search",methods = [ "GET","POST" ])
def electronicSearch():
    resp = { 'code':20000,'message':'操作成功~', 'data':{}}

    req = request.values
    name = req['name'] if 'name' in req else ''
    page = int( req['page'] ) if 'page' in req else 0
    limit = int( req['limit'] ) if 'limit' in req else 0
    datetimeStart = req['datetimeStart'][:19].replace('T',' ') if 'datetimeStart' in req else ''
    datetimeEnd = req['datetimeEnd'][:19].replace('T',' ') if 'datetimeEnd' in req else ''

    # 分页偏移量
    offset = ( page - 1 ) * limit

    if datetimeStart and not datetimeEnd:
        datetimeEnd = '3000-01-01 00:00:00'
    if datetimeEnd and not datetimeStart:
        datetimeStart = '1970-01-01 00:00:00'
    if not datetimeEnd and not datetimeStart:
        datetimeStart = '1970-01-01 00:00:00'
        datetimeEnd = '3000-01-01 00:00:00'

    logger.info(datetimeStart)
    logger.info(datetimeEnd)
    # 获取总数
    total = db.session.query(
        Electronic,
        Project.name,
        Product.name,
        Supplier.name)\
        .filter( Electronic.project_id == Project.id )\
        .filter( Electronic.supplier_id == Supplier.id )\
        .filter( Product.project_id == Project.id )\
        .filter( Electronic.status == 1 )\
        .filter( Electronic.created_time >= datetimeStart, Electronic.created_time <= datetimeEnd )\
        .filter( func.concat(Electronic.name, Electronic.position, Project.name, Product.name).op('regexp')('.*%s.*'%name.replace(' ','.*')) )\
        .order_by(Electronic.name)\
        .count()

    electronic_list = db.session.query(
        Electronic,
        Project.name,
        Product.name,
        Supplier.name)\
        .filter( Electronic.project_id == Project.id )\
        .filter( Electronic.supplier_id == Supplier.id )\
        .filter( Product.project_id == Project.id )\
        .filter( Electronic.status == 1 )\
        .filter( Electronic.created_time >= datetimeStart, Electronic.created_time <= datetimeEnd )\
        .filter( func.concat(Electronic.name, Electronic.position, Project.name).op('regexp')('.*%s.*'%name.replace(' ','.*')) )\
        .order_by(Electronic.name)\
        .offset( offset ).limit( limit ).all()

    data_electronic_list = []
    if electronic_list:
        for item in electronic_list:
            electronic = item[0]
            project = item[1]
            product = item[2]
            supplier = item[3]
            tmp_data = {
                'id':electronic.id,
                'name':electronic.name,
                'sn':electronic.sn,
                'package':electronic.package,
                'price':str(electronic.price),
                'stock':electronic.stock,
                'position':electronic.position,
                'created_time':getFormatDate(electronic.created_time),
                'project':project,
                'product':product,
                'supplier':supplier
            }
            data_electronic_list.append( tmp_data  )

    # projects = [ {'value':p.id, 'label':p.name} for p in db.session.query(Project).all() ]
    # products = [ {'value':p.id, 'label':p.name} for p in db.session.query(Product).all() ]
    boom = [ {'value':p.id, 'label':p.name} for p in db.session.query(ElectronicBoom).all() ]

    resp['data']['items'] = data_electronic_list
    resp['data']['total'] = total
    resp['data']['booms'] = booms
    #  resp['data']['products'] = products
    print(resp)

    return jsonify( resp )

@route_api.route("/electronic/info",methods = [ "GET","POST" ])
def electronicInfo():
    resp = { 'code':20000,'message':'操作成功~', 'data':{}}

    req = request.values
    sn = req['sn'] if 'sn' in req else ''
    if not sn:
        resp['code'] = -1
        resp['message'] = '需要sn'
        return jsonify( resp )

    item = db.session.query(
        Electronic,
        Project.name,
        Product.name,
        Supplier.name)\
        .filter( Electronic.project_id == Project.id )\
        .filter( Electronic.supplier_id == Supplier.id )\
        .filter( Product.project_id == Project.id )\
        .filter( Electronic.status == 1 )\
        .filter( Electronic.sn == sn )\
        .first()
    if not item:
        resp['code'] = -1
        resp['message'] = '设备信息不存在'
        return jsonify( resp )

    electronic = item[0]
    project = item[1]
    product = item[2]
    supplier = item[3]
    resp['data']= {
        'id':electronic.id,
        'name':electronic.name,
        'sn':electronic.sn,
        'package':electronic.package,
        'price':str(electronic.price),
        'stock':electronic.stock,
        'position':electronic.position,
        'created_time':getFormatDate(electronic.created_time),
        'project':project,
        'product':product,
        'supplier':supplier
    }

    return jsonify( resp )

@route_api.route("/electronic/delete",methods = [ "GET","POST" ])
def electronicDelete():
    resp = { 'code':20000,'message':'删除成功~', 'data':{}}

    req = request.values
    sn = req['sn'] if 'sn' in req else ''

    if not sn:
        resp['code'] = -1
        resp['message'] = '需要sn'
        return jsonify( resp )

    electronic_info = Electronic.query.filter_by( sn=sn ).first()
    if not electronic_info:
        resp['code'] = -1
        resp['message'] = '设备信息不存在'
        return jsonify( resp )

    db.session.delete(electronic_info)
    db.session.commit()

    return jsonify( resp )


@route_api.route("/electronic/edit",methods = [ "GET","POST" ])
def electronicEdit():
    resp = { 'code':20000,'message':'编辑元器件成功~', 'data':{}}

    req = request.values
    sn = req['sn'] if 'sn' in req else ''

    if not sn:
        resp['code'] = -1
        resp['message'] = '需要sn~'
        return jsonify( resp )

    electronic_info = Electronic.query.filter_by( sn=sn ).first()
    if not electronic_info:
        resp['code'] = -1
        resp['message'] = '设备信息不存在~'
        return jsonify( resp )

    project = req['project'] if 'project' in req else ''
    project_info = Project.query.filter_by( name=project ).first()
    if not project_info:
        resp['code'] = -1
        resp['message'] = '项目不存在,请添加~'
        return jsonify( resp )

    product = req['product'] if 'product' in req else ''
    product_info = Product.query.filter_by( name=product ).first()
    if not product_info:
        resp['code'] = -1
        resp['message'] = '产品不存在,请添加~'
        return jsonify( resp )

    supplier = req['supplier'] if 'supplier' in req else ''
    supplier_info = Supplier.query.filter_by( name=supplier ).first()
    if not supplier_info:
        resp['code'] = -1
        resp['message'] = '供货商不存在,请添加~'
        return jsonify( resp )

    electronic_info.name = req['name']
    electronic_info.package = req['package']
    electronic_info.price = decimal.Decimal( float(req['price'] if 'price' in req else 0) )
    electronic_info.stock = int(req['stock'])
    electronic_info.position = req['position']
    electronic_info.project_id = project_info.id
    electronic_info.product_id = product_info.id
    electronic_info.supplier_id = supplier_info.id

    db.session.commit()
    return jsonify( resp )


@route_api.route("/electronic/add",methods = [ "GET","POST" ])
def electronicAdd():
    resp = { 'code':20000,'message':'添加元器件成功~', 'data':{}}
    req = request.values

    project = req['project'] if 'project' in req else ''
    project_info = Project.query.filter_by( name=project ).first()
    if not project_info:
        resp['code'] = -1
        resp['message'] = '项目不存在,请添加~'
        return jsonify( resp )

    product = req['product'] if 'product' in req else ''
    product_info = Product.query.filter_by( name=product ).first()
    if not product_info:
        resp['code'] = -1
        resp['message'] = '产品不存在,请添加~'
        return jsonify( resp )

    supplier = req['supplier'] if 'supplier' in req else ''
    supplier_info = Supplier.query.filter_by( name=supplier ).first()
    if not supplier_info:
        resp['code'] = -1
        resp['message'] = '供货商不存在,请添加~'
        return jsonify( resp )

    electronic_model              = Electronic()
    electronic_model.name         = req['name']
    electronic_model.sn           = ElectronicService.geneSn()
    electronic_model.package      = req['package']
    try:
        electronic_model.price    = decimal.Decimal( float(req['price'] if 'price' in req else 0) )
    except:
        pass
    electronic_model.stock        = int(req['stock'])
    electronic_model.position     = req['position']

    electronic_model.project_id   = project_info.id
    electronic_model.product_id   = product_info.id
    electronic_model.supplier_id  = supplier_info.id

    electronic_model.status       = 1
    electronic_model.updated_time = electronic_model.created_time = getCurrentDate()

    db.session.add( electronic_model )
    db.session.commit()

    user_id = str(request.headers['X-Token']).split('#')[1]
    if not user_id:
        resp['code'] = -1
        resp['message'] = 'token错误~'
        return jsonify( resp )

    res = ElectronicService.setInStockLog(
                        user_id = int(user_id),
                        electronic_id = int(electronic_model.id),
                        count = int(req['stock']),
                        note = req['note'])
    if not res:
        resp['code'] = -1
        resp['message'] = '添加入库记录错误~'
        return jsonify( resp )

    return jsonify( resp )


@route_api.route("/electronic/out/cart/add",methods = [ "GET","POST" ])
def electronicOutCartAdd():
    resp = { 'code':20000,'message':'加入出库单成功~', 'data':{}}
    req = request.values

    sn = req['sn'] if 'sn' in req else ''
    if not sn:
        resp['code'] = -1
        resp['message'] = '需要sn'
        return jsonify( resp )

    electronic_info =  Electronic.query.filter_by( sn = sn  ).first()
    if not electronic_info:
        resp['code'] = -1
        resp['message'] = '元器件不存在,添加失败~'
        return jsonify( resp )

    user_info = UserService.getUserInfo(request)
    if not user_info:
        resp['code'] = -1
        resp['message'] = '用户不存在，添加失败~'
        return jsonify( resp )

    cart_info =  ElectronicOutCart.query.filter( ElectronicOutCart.electronic_id == Electronic.id  )\
                        .filter( Electronic.sn == sn  )\
                        .first()
    if cart_info:
        resp['code'] = -1
        resp['message'] = '当前元器件已添加至出库单中，无需重复添加~'
        return jsonify( resp )

    cart_model = ElectronicOutCart()
    cart_model.user_id = user_info.id
    cart_model.electronic_id = electronic_info.id
    cart_model.count = 0
    cart_model.updated_time = cart_model.created_time = getCurrentDate()
    db.session.add(cart_model)
    db.session.commit()

    return jsonify( resp )


